
#include "jxos_config.h"
#if (JXOS_TASK_ENABLE == 1)
#include "kernel/jxos_task.h"
#endif

#if (JXOS_SYS_SERVICE_SOFTWARE_TIMER_TASK_ENABLE == 1)
#include "driver/sim_timer.h"

void sys_software_timer_task_hal_init_config(void);
void sys_software_timer_task_hal_start_config(void);
void sys_software_timer_task_hal_stop_config(void);

static uint8_t sim_timer_index_count;
bool_t software_timer_task_tick_handler_flag;

#if (JXOS_Compiler_optimization_1 == 1)
#if (JXOS_TASK_ENABLE == 1)
static void software_timer_task(void)
#else
void sys_software_timer_task(void)
#endif
#else
static void software_timer_task(uint8_t task_id, void * parameter)
#endif
{
	if(software_timer_task_tick_handler_flag == true){
		software_timer_task_tick_handler_flag = false;
        sim_timer_tick_hander();
    }
}

void sys_software_timer_task_init(void)
{
	sys_software_timer_task_hal_init_config();
    
	software_timer_task_tick_handler_flag = false;
    sim_timer_index_count = 0;

    sim_timer_init();
	sys_software_timer_task_hal_start_config();

#if (JXOS_TASK_ENABLE == 1)
	jxos_task_create(software_timer_task, "swt_t", 0);
#endif
}

/*******************************************************/
void* sys_software_timer_task_new_timer(void)
{
    uint8_t index = 0;
    if(sim_timer_index_count < SWTIMER_MAX){
        sim_timer_index_count++;
        index = sim_timer_index_count;
    }
    return (void*)index;
}

void sys_software_timer_task_set_timer(void* swtime, uint16_t time)
{   
    uint8_t i = (uint8_t)swtime;
    if((i <= sim_timer_index_count)&&(i != 0)){
    	i--;
        time = time/TIMER_CONSTANT_INTERVAL_MS;
        sim_timer_set_timeout(i, time);
    }
}

void sys_software_timer_task_start_timer(void* swtime)
{
    uint8_t i = (uint8_t)swtime;
    if((i <= sim_timer_index_count)&&(i != 0)){
    	i--;
        sim_timer_start(i);
    }
}

void sys_software_timer_task_stop_timer(void* swtime)
{
    uint8_t i = (uint8_t)swtime;
    if((i <= sim_timer_index_count)&&(i != 0)){
    	i--;
        sim_timer_stop(i);
    }
}

void sys_software_timer_task_restart_timer(void* swtime)
{
    uint8_t i = (uint8_t)swtime;
    if((i <= sim_timer_index_count)&&(i != 0)){
    	i--;
        sim_timer_restart(i);
    }
}

bool_t sys_software_timer_task_check_running_timer(void* swtime)
{
    uint8_t i = (uint8_t)swtime;
    if((i <= sim_timer_index_count)&&(i != 0)){
    	i--;
        i = sim_timer_check_running(i);
    }
    return (bool_t)i;
}

bool_t sys_software_timer_task_check_overtime_timer(void* swtime)
{
    uint8_t i = (uint8_t)swtime;
    if((i <= sim_timer_index_count)&&(i != 0)){
    	i--;
        i = sim_timer_check_overtime(i);
    }
    return (bool_t)i;
}

#endif
